<?php

namespace Api\Controller;

use Think\Controller;

// 跨域
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Headers:x-requested-with, content-type,token');
class CommonController extends Controller
{


    // 上传文件
    function upload()
    {
        $upload = new \Think\Upload(); // 实例化上传类
        $upload->maxSize   =     104857600; // 设置附件上传大小
        // $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg','zip',); // 设置附件上传类型
        $upload->rootPath  =     '../Uploads/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件 
        $info   =   $upload->upload();
        if (!$info) {
            $this->ajaxReturn(['state' => 0, 'info' => '上传失败 : ' . $upload->getError()]);
        } else {
            $file = $info['file'];
            $file['path'] = '/Uploads/' . $file['savepath'] . $file['savename'];
            $this->ajaxReturn(['state' => 1, 'info' => '上传成功', 'data' => $file]);
        }
    }

    // 所有函数入口
    function _initialize()
    {
        // 白名单
        $whitelist = ['upload'];
        $url = explode('/', $_SERVER['PATH_INFO']);
        $method = $url[count($url) - 1];
        // 需要验证token
        if (!in_array($method, $whitelist)) {
            $token = $_SERVER['HTTP_TOKEN'];
            $where['token'] = $token;
            $where['expire_time'] = ['gt', date("Y-m-d H:i:s")];
            $login = M('login')->where($where)->find();
            if (!$login) $this->ajaxReturn(['state' => 0, 'info' => '登录已失效 , 请重新登录']);
        }
    }
}
